package lucky.xiong.多线程;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * CAS 比较并交换
 * Compare and Swap
 * 本demo具体资料，查看oneNote - 大的笔记本 - 面试题和笔记 - CAS是什么
 * @author XiongJL
 * @date 2021/6/30 15:23
 *
 **/
public class CASDemo {

    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(5);
        // 期望值为5，变更为2019. 即期望原来的值没人动过
        System.out.println(atomicInteger.compareAndSet(5, 2019)+"\t current data: "+atomicInteger.get());
        System.out.println(atomicInteger.compareAndSet(5, 1024)+"\t current data: "+atomicInteger.get());

        // 解决多线程情况下  number++ 的线程安全的问题
        atomicInteger.getAndIncrement();

        /**
         * package java.util.concurrent.atomic.AtomicInteger
         *  Atomically increments by one the current value.
         *
         *  @return the previous value
         *
         *  valueOffset 内存偏移量，即当前内存地址
         *  public final int getAndIncrement () {
         *   return unsafe.getAndAddInt(this, valueOffset, 1);
         * }
         */

        /**
         * package sun.misc.Unsafe
         *
         *  public final int getAndAddInt(Object var1, long var2, int var4) {
         *         int var5;
         *         do {
         *             var5 = this.getIntVolatile(var1, var2);
         *         } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
         *
         *         return var5;
         *     }
         *
         */

    }
}
